import time

from django.shortcuts import render, HttpResponse, redirect
from web.forms.project import ProjectModelForm
from django.http import JsonResponse
from utils.tencent.cos import create_bucket
from web import models


def project_list(request):
    """项目列表"""
    # GET : 查看项目列表
    if request.method == 'GET':
        # 获取当前用户创建的所有项目
        project_dict = {
            'star': [],
            'my': [],
            'join': [],
        }

        my_project_list = models.Project.objects.filter(creator=request.tracer.user)
        for item in my_project_list:
            if item.star:
                project_dict['star'].append({'value': item, 'type': 'my'})
            else:
                project_dict['my'].append(item)

        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
        for item in join_project_list:
            if item.star:
                project_dict['star'].append({'value': item.project, 'type': 'join'})
            else:
                project_dict['join'].append(item.project)

        form = ProjectModelForm(request)
        return render(request, 'project_list.html', {'form': form, 'project_dict': project_dict})

    # POST : 创建项目
    form = ProjectModelForm(data=request.POST, request=request)
    if form.is_valid():
        # 为项目创建一个桶
        bucket = f'{request.tracer.user.mobile_phone}-{str(int(time.time()))}-1317332932'
        region = 'ap-nanjing'
        create_bucket(bucket, region)
        # 把桶和区域写入数据库
        form.instance.bucket = bucket
        form.instance.region = region
        form.instance.creator = request.tracer.user

        form.save()
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


"""
查看项目列表
星标项目
"""


def project_star(request, project_type, project_id):
    """星标项目"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return redirect('project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)
        return redirect('project_list')
    return HttpResponse("请求错误")


def project_unstar(request, project_type, project_id):
    """取消星标项目"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect('project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
        return redirect('project_list')
    return HttpResponse("请求错误")
